package com.unionftech.common.recaptcha.aliyun

import android.app.Activity
import android.content.Context

class AliyunCaptcha private constructor() {
    private var mConfig: AliyunCaptchaConfig? = null
    private var mDialog: AliyunCaptChaDialog? = null

    companion object {
        @Volatile
        private var instance: AliyunCaptcha? = null

        @JvmStatic
        fun getInstance() = instance ?: synchronized(AliyunCaptcha::class.java) {
            instance ?: AliyunCaptcha().also {
                instance = it
            }
        }
    }

    fun init(config: AliyunCaptchaConfig) {
        mConfig = config
        checkConfig(mConfig)
        crateDialog()
    }

    private fun crateDialog() {
        if (mConfig != null) {
            this.mDialog = AliyunCaptChaDialog(mConfig!!)
        }
    }

    private fun checkConfig(config: AliyunCaptchaConfig?) {
        if (config != null) {
            if (config.listener != null) {
                var var2: Context?
                if (config.context.also { var2 = it } != null) {
                    require(var2 is Activity) { "Context must be activity type !" }
                } else {
                    throw java.lang.IllegalArgumentException("Context cannot be null !")
                }
            } else {
                throw java.lang.IllegalArgumentException("AliyunCaptchaListener cannot be null !")
            }
        } else {
            throw IllegalArgumentException("AliyunCaptchaConfig cannot be null !")
        }
    }


    fun validate() {
        mDialog?.let {
            if (!it.isShowing) {
                it.show()
            }
        }
    }

    fun destroy() {
        if (mConfig != null) {
            mConfig?.context = null
            mConfig?.listener = null
            mConfig = null
        }
        if (mDialog != null) {
            if (mDialog!!.isShowing) {
                mDialog!!.dismiss()
            }
            mDialog = null
        }
    }
}